﻿namespace FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers.Final
{
    using FiftyOne.Foundation.Mobile.Detection.Wurfl;
    using FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers;
    using System;
    using System.Collections.Generic;

    internal class Matcher
    {
        internal static DeviceInfo Match(string userAgent, Results results)
        {
            int num = 0;
            int pos = 0;
            List<DeviceInfo> devices = new List<DeviceInfo>();
            foreach (Result result in results)
            {
                int num3 = (result.Device.UserAgent.Length > userAgent.Length) ? userAgent.Length : result.Device.UserAgent.Length;
                num = 0;
                while (num < num3)
                {
                    if (userAgent[num] != result.Device.UserAgent[num])
                    {
                        break;
                    }
                    num++;
                }
                if (num > pos)
                {
                    pos = num;
                    devices.Clear();
                    devices.Add(result.Device);
                }
                else if (num == pos)
                {
                    devices.Add(result.Device);
                }
            }
            if (devices.Count == 1)
            {
                return devices[0];
            }
            if (devices.Count > 1)
            {
                return MatchTails(userAgent, pos, devices);
            }
            return null;
        }

        private static DeviceInfo MatchTails(string userAgent, int pos, List<DeviceInfo> devices)
        {
            int length = 0;
            Queue<string> queue = new Queue<string>();
            foreach (DeviceInfo info in devices)
            {
                string item = info.UserAgent.Substring(pos, info.UserAgent.Length - pos);
                queue.Enqueue(item);
                if (item.Length > length)
                {
                    length = item.Length;
                }
            }
            string str2 = userAgent.Substring(pos, ((length + pos) < userAgent.Length) ? length : (userAgent.Length - pos));
            string str3 = null;
            int maxValue = 0x7fffffff;
            while (queue.Count > 0)
            {
                string str4 = queue.Dequeue();
                int num3 = Algorithms.EditDistance(str2, str4, maxValue);
                if (num3 < maxValue)
                {
                    maxValue = num3;
                    str3 = str4;
                }
            }
            foreach (DeviceInfo info in devices)
            {
                if (info.UserAgent.EndsWith(str3))
                {
                    return info;
                }
            }
            return devices[0];
        }
    }
}

